# Importing Data
ITALY <- read_excel("C:/Users/Biniam/Desktop/Documents/Academic/Thesis/Analysis Folder/Excel Files/Saudi Arabia/Italy.xlsx")

# Checking the Imported Data
View(ITALY)

# Creating Time Series Data
ITALY_ts <- ts(ITALY, start=c(2004,01), end=c(2019,06), frequency=12)

# Viewing and Checking the Created Time Series Data
ITALY_ts
sum(is.na(ITALY_ts))
library(forecast)
ITALY_ts <- tsclean(ITALY_ts)

# Step – 1 of the Box-Jenkins Methodology (Identification: Plotting the Time Series Data)
plot(ITALY_ts)
plot(aggregate(ITALY_ts,FUN=mean))

# Decomposing
ITALY_ts_decomp <- decompose(ITALY_ts)
plot(ITALY_ts_decomp)

# Testing for Stationarity
acf(ITALY_ts, lag.max=20)
pacf(ITALY_ts, lag.max=20)

# To see any seasonal effect
boxplot(ITALY_ts~cycle(ITALY_ts))

# To remove trend effect
ITALY_ts_diff <- diff(ITALY_ts)
plot(ITALY_ts_diff)

# To remove variance effect
ITALY_ts_log <- log(ITALY_ts)
plot(ITALY_ts_log)

# To remove both (Trend and Variance) effects
ITALY_ts_both <- diff(log(ITALY_ts))
plot(ITALY_ts_both)


# Dealing with ACF and PACF
install.packages("tseries")
library(tseries)
acf(ITALY_ts, lag.max=20)
acf(log(ITALY_ts), lag.max=20)
acf(diff(ITALY_ts), lag.max=20)
acf(diff(log(ITALY_ts)), lag.max=20)
pacf(ITALY_ts, lag.max=20)
pacf(log(ITALY_ts), lag.max=20)
pacf(diff(ITALY_ts), lag.max=20)
pacf(diff(log(ITALY_ts)), lag.max=20)

# Step-2 of the Box-Jenkins Methodology (Estimating the appropriate model)
ITALY_ts_model <- auto.arima(ITALY_ts)
ITALY_ts_model
ITALY_ts_model <- auto.arima(ITALY_ts, ic="aic", trace = TRUE)
ITALY_ts_model

# Step-3 of the Box-Jenkins Methodology (Diagnosis Checking)
library(tseries)
plot.ts(ITALY_ts_model$resid)
acf(ITALY_ts_model$residuals, main='ACF Residual')
pacf(ITALY_ts_model$residuals, main='ACF Residual')
Box.test(ITALY_ts_model$resid, lag=20, type="Ljung-Box")

# Forecasting
options(max.print=1000000)
library(forecast)
ITALY_ts_forecast <- forecast (ITALY_ts_model, level=c(95), h=258)
plot(ITALY_ts_forecast)
ITALY_ts_forecast             


write.table(ITALY_ts_forecast, file="Italy_TSA.csv", sep=",")
